﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using TallyBook.DesignLib.Attributes;

namespace TallyBook.BLL.Service.CommonImp
{
    public class DataGridViewService
    {
        /// <summary>
        ///     DataGridView反射分装方法
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public DataGridViewColumn[] BindColumns(Type type)
        {
            return type.GetProperties().Where(item =>
            {
                var attrs = item.GetCustomAttributes(typeof(ForeignerKeyAttribute), false);
                if (attrs.Length == 0)
                    return true;
                var foreignerKey = attrs[0] as ForeignerKeyAttribute;
                if (foreignerKey == null)
                    return true;
                return false;
            }).Select(item =>
            {
                object[] customAttributes = item.GetCustomAttributes(typeof (DescriptionAttribute), false);
                var desc = customAttributes[0] as DescriptionAttribute;
                var property = new DataGridViewTextBoxColumn
                {
                    Name = item.Name,
                    HeaderText = desc.Description,
                    DataPropertyName = item.Name,
                };
                return property;
            }).ToArray();

            //return type.GetProperties().Where(item =>
            //{
            //    var customAttributes = item.GetCustomAttributes(typeof(ForeignerKeyAttribute), false);

            //    if (customAttributes.Length == 0)
            //        return true;
            //    var desc = customAttributes[0] as ForeignerKeyAttribute;
            //    if (desc == null)
            //        return true;
            //    return false;
            //}).Select(item =>
            //{
            //    var customAttributes = item.GetCustomAttributes(typeof (DescriptionAttribute), false);
            //    var desc = customAttributes[0] as DescriptionAttribute;
            //    DataGridViewTextBoxColumn property = new DataGridViewTextBoxColumn
            //    {
            //        Name = item.Name,
            //        HeaderText = desc.Description,
            //        DataPropertyName = item.Name,
            //    };
            //    return property;
            //}).ToArray();
        }
    }
}